package com.example.questionsystem.modules.qu.util;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;

import java.io.*;
import java.util.regex.*;
import java.util.*;

public class AnswerConverter {

    public static void main(String[] args) {
        try {
            // 文件路径配置
            String wordPath = "D:\\test.docx";   // Word文档路径
            String excelPath = "D:\\output.xlsx"; // 输出Excel路径
            
            // 1. 从Word提取答案文本
            String answerText = extractAnswerText(wordPath);
            
            // 2. 解析答案为列表
            List<String> answers = parseAnswers(answerText);
            
            // 3. 写入Excel文件
            writeToExcel(answers, excelPath);
            
            System.out.println("转换成功！保存至: " + excelPath);
            System.out.println("共转换 " + answers.size() + " 个答案");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static String extractAnswerText(String filePath) throws IOException {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument doc = new XWPFDocument(fis)) {

            StringBuilder content = new StringBuilder();

            // 提取所有段落文本
            for (XWPFParagraph p : doc.getParagraphs()) {
                String text = p.getText().trim();
                if (!text.isEmpty()) {
                    content.append(text).append("\n");
                }
            }

            // 提取所有表格文本
            for (XWPFTable table : doc.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph p : cell.getParagraphs()) {
                            String text = p.getText().trim();
                            if (!text.isEmpty()) {
                                content.append(text).append("\n");
                            }
                        }
                    }
                }
            }

            String fullText = content.toString();
            System.out.println("从Word提取的文本内容:\n" + fullText);
            return fullText;
        }
    }

    private static List<String> parseAnswers(String text) {
        List<String> answerList = new ArrayList<>();

        // 增强版正则表达式：更全面地匹配答案格式
        Pattern pattern = Pattern.compile(
                "(?:^|\\s|\\n)" +         // 开头或空白或换行
                        "(\\d+)" +                // 题号
                        "\\s*[.、:：]?\\s*" +      // 分隔符（支持多种形式）
                        "([A-Za-z]{1,5})" +       // 答案（1-5个字母，支持小写）
                        "(?=\\s|\\n|$)"            // 后面是空白、换行或结束
        );

        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            String number = matcher.group(1);
            String answer = matcher.group(2).toUpperCase(); // 统一转为大写

            // 构建标准化答案格式
            String normalized = number + "." + answer;
            answerList.add(normalized);

            System.out.println("匹配到答案: " + normalized);
        }

        // 按题号排序
        answerList.sort(Comparator.comparingInt(s ->
                Integer.parseInt(s.substring(0, s.indexOf('.')))
        ));

        return answerList;
    }

    private static void writeToExcel(List<String> answers, String filePath) throws IOException {
        try (XSSFWorkbook workbook = new XSSFWorkbook()) {
            XSSFSheet sheet = workbook.createSheet("答案");

            // 创建标题行
            XSSFRow header = sheet.createRow(0);
            header.createCell(0).setCellValue("题号");
            header.createCell(1).setCellValue("答案");
            header.createCell(2).setCellValue("类型");

            // 填充数据
            for (int i = 0; i < answers.size(); i++) {
                XSSFRow row = sheet.createRow(i + 1);
                String[] parts = answers.get(i).split("\\.", 2);

                if (parts.length >= 2) {
                    row.createCell(0).setCellValue(parts[0]); // 题号
                    row.createCell(1).setCellValue(parts[1]); // 答案

                    // 判断题目类型
                    String type = (parts[1].length() > 1) ? "多选题" : "单选题";
                    row.createCell(2).setCellValue(type);
                }
            }

            // 自动调整列宽
            for (int i = 0; i < 3; i++) {
                sheet.autoSizeColumn(i);
            }

            // 保存文件
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                workbook.write(fos);
            }
        }
    }
}